<template>
  <div>
    <PageHeader :title="$t('articleManage.编辑文章')" />
    <div class="form-container">
      <LangTabs v-model="lang" />
      <el-form
        :model="formData"
        label-width="100px"
        ref="formRef"
        :rules="rules"
      >
        <el-form-item :label="$t('articleManage.文章标题')" :prop="'title' + lang">
          <el-input
            v-model="formData['title' + lang]"
            style="width: 300px"
            :placeholder="$t('articleManage.请输入文章标题')"
          />
        </el-form-item>
        <el-form-item :label="$t('articleManage.文章内容')" :prop="'content' + lang">
          <EditorWang v-if="showEditorWang" v-model="formData['content' + lang]" />
        </el-form-item>
      </el-form>

      <div class="flex_aic_jcc">
        <el-button @click="handleBack">{{ $t('articleManage.返回') }}</el-button>
        <el-button type="primary" @click="submitForm">{{ $t('articleManage.保存并返回') }}</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from "vue";
import EditorWang from "@/components/editorWang.vue";
import { useRouter, useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { setAttrLangs } from "@/i18n/tools";
import Api from "@/config/api/api";
import LangTabs from "@/components/langTabs.vue";
import { ElMessage } from "element-plus";

const { locale, t } = useI18n();
const lang = ref(locale.value);
const router = useRouter();
const route = useRoute();
const formData = ref({});
const rules = ref({});
const showEditorWang = ref(true);

setAttrLangs(formData.value, "title", "");
setAttrLangs(formData.value, "content", "");
setAttrLangs(rules.value, "title", [
  { required: true, message: t('articleManage.请输入文章标题') },
]);
setAttrLangs(rules.value, "content", [
  { required: true, message: t('articleManage.请输入文章内容') },
]);
const formRef = ref(null);
const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      Api.articleUpdate(formData.value).then((res) => {
        if (res.status === 200) {
          ElMessage.success(t('articleManage.保存成功'));
          router.back();
        }
      });
    }
  });
};
const handleBack = () => {
  router.back();
};

const getArticle = () => {
  Api.articleDetail(route.query.code).then((res) => {
    if (res.status === 200) {
      formData.value = res.data;
    }
  });
};

onMounted(() => {
  getArticle();
});

watch(
  () => lang.value,
  () => {
    showEditorWang.value = false;
    nextTick(() => {
      showEditorWang.value = true;
    });
  }
);
</script>

<style scoped></style>
